package com.sky.service.user.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.mapper.user.ShoppingCartMapper;
import com.sky.pojo.ShoppingCart;
import com.sky.service.admin.DishService;
import com.sky.service.admin.SetMealService;
import com.sky.service.user.ShoppingCartService;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetMealService setMealService;

    @Override
    public void add(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .createTime(LocalDateTime.now())
                .dishId(shoppingCartDTO.getDishId())
                .setmealId(shoppingCartDTO.getSetmealId())
                .dishFlavor(shoppingCartDTO.getDishFlavor())
                .userId(BaseContext.getCurrentId())
                .build();
        ShoppingCart exit = shoppingCartMapper.findByDishIdOrSetmealId(shoppingCart);
        if (exit != null) {
            log.info("商品已存在{}，数量+1",exit.getName());
            shoppingCartMapper.updateNum(exit.getId(),1);
            return;
        }
        if(shoppingCart.getDishId()!=null){
            //菜品
            DishVO dishVO = dishService.findById(shoppingCart.getDishId());
            shoppingCart.setAmount(dishVO.getPrice());
            shoppingCart.setImage(dishVO.getImage());
            shoppingCart.setName(dishVO.getName());
        }else {
            //套餐
            SetmealVO setmealVO = setMealService.findById(shoppingCart.getSetmealId());
            shoppingCart.setAmount(setmealVO.getPrice());
            shoppingCart.setImage(setmealVO.getImage());
            shoppingCart.setName(setmealVO.getName());
        }
        shoppingCart.setNumber(1);
        shoppingCartMapper.insert(shoppingCart);
    }

    @Override
    public List<ShoppingCart> list() {
        return shoppingCartMapper.list(BaseContext.getCurrentId());
    }

    @Override
    public void clean() {
        shoppingCartMapper.clean(BaseContext.getCurrentId());
    }
}
